<template>
  <div>
    <!-- 行内表单 -->
    <el-form :inline="true" style="margin: 10px 0">
      <el-form-item>
        <el-input placeholder="用户名" v-model="searchobj.username"></el-input>
      </el-form-item>
      <el-button type="primary" icon="el-icon-search" @click="this.getUser"
        >查询</el-button
      >
      <el-button @click="empty">清空</el-button>
    </el-form>
    <!-- 添加和批量删除的按钮 -->
    <div>
      <el-button type="primary" @click="add">添加</el-button>
      <el-button
        type="danger"
        @click="deletion"
        :disabled="this.selectId.length === 0"
        >批量删除</el-button
      >
    </div>
    <!-- 表格区域 -->
    <el-table
      ref="multipleTable"
      :data="tableList"
      tooltip-effect="dark"
      style="width: 100%"
      v-loading="listLoading"
      @selection-change="handleSelectionChange"
      border
      width="100%"
      class="tab"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column
        type="index"
        width="80"
        label="序号"
        align="center"
      ></el-table-column>
      <el-table-column
        label="用户名"
        width="120"
        prop="username"
      ></el-table-column>
      <el-table-column
        label="用户昵称"
        width="width"
        prop="nickName"
      ></el-table-column>
      <el-table-column
        label="权限列表"
        width="width"
        prop="roleName"
      ></el-table-column>
      <el-table-column
        label="创建时间"
        width="width"
        prop="gmtCreate"
      ></el-table-column>
      <el-table-column
        label="更新时间"
        width="width"
        prop="gmtModified"
      ></el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template slot-scope="{ row, $index }">
          <el-button
            type="info"
            icon="el-icon-user-solid"
            size="mini"
            title="分配角色"
            @click="showAssignRole(row)"
          ></el-button>
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            title="修改用户"
            @click="UpdateUser(row)"
          ></el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            title="删除用户"
            @click="removeUser(row.id)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 底部分页区域 -->
    <el-pagination
      style="margin-top: 20px; textalign: center"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[3, 5, 10]"
      :page-size="limit"
      :page-count="7"
      layout=" prev, pager, next, jumper,->,sizes, total"
      :total="total"
    >
    </el-pagination>

    <!-- 添加的对话框 -->
    <el-dialog title="添加用户" :visible.sync="adddialogFormVisible">
      <el-form
        :model="Userform"
        :rules="UserformRules"
        ref="ruleForm"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="Userform.username"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="Userform.nickName"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input v-model="Userform.password"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色的对话框 -->
    <el-dialog title="设置角色" :visible.sync="AssignRoledialogFormVisible">
      <el-form label-width="100px">
        <el-form-item label="用户名">
          <el-input disabled v-model="Roleform.username"></el-input>
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <div style="margin: 15px 0"></div>
          <el-checkbox-group
            v-model="userRoleIds"
            @change="handleCheckedChange"
          >
            <el-checkbox
              v-for="item in allRoles"
              :key="item.id"
              :label="item.id"
              >{{ item.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="AssignRoledialogFormVisible = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="saveassignRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户的对话框 -->
    <el-dialog title="修改用户" :visible.sync="UpdatedialogFormVisible">
      <el-form :model="Updateform" :rules="Updaterules" ref="UpdateRef">
        <el-form-item
          label="用户名"
          prop="username"
          label-width="formLabelWidth"
        >
          <el-input v-model="Updateform.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" label-width="formLabelWidth">
          <el-input v-model="Updateform.nickName" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="UpdatedialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="ReviseUser"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      page: 1, //当前页
      limit: 5, //每页展示多少条数据
      total: 0, //总的数据条数
      searchobj: {
        username: "",
      },
      //加载表格数据前有个loading效果
      listLoading: false,
      //表格数据
      tableList: [],
      selectId: [], //所有选中的表格数据的数组
      adddialogFormVisible: false, //控制添加对话框的显示与隐藏
      AssignRoledialogFormVisible: false, //控制分配角色对话框的显示与隐藏
      //添加对话框的表单对象
      Userform: {
        username: "",
        nickName: "",
        password: "",
      },
      //添加对话框的表单验证规则对象
      UserformRules: {
        username: [
          { required: true, message: "用户名必须输入" },
          { min: 4, message: "用户名不能小于4位" },
        ],
        password: [{ required: true, validator: this.validatePassword }],
      },
      //当前要操作的用户
      Roleform: {},
      isIndeterminate: true, //实现全选的效果
      checkAll: false, //是否全选
      allRoles: [], //所有的角色列表
      userRoleIds: [], // 用户的角色ID的列表
      UpdatedialogFormVisible: false, //控制修改用户对话框的显示与隐藏
      Updateform: {
        username:"",
        nickName:"",
      }, //修改用户对话框的表单对象
      Updaterules:{
        username:[
           { required: true, message: '用户名必须输入' },
          { min: 4, message: '用户名不能小于4位' }
        ]
      },//修改用户的表单验证规则对象
    };
  },
  mounted() {
    this.getUser();
  },
  methods: {
    //获取用户管理表格数据
    async getUser() {
      const { page, limit, searchobj } = this;
      this.listLoading = true;
      const result = await this.$API.user.getUserList(page, limit, searchobj);
      console.log(result, "获取的用户管理表格的数据");
      this.listLoading = false;
      this.tableList = result.data.items;
      this.total = result.data.total;
    },
    //点击清空按钮触发的事件
    empty() {
      this.searchobj.username = "";
    },
    //点击添加按钮触发的事假
    add() {
      this.adddialogFormVisible = true;
    },
    //每页显示多少条数据发生变化触发
    handleSizeChange(limit) {
      this.limit=limit;
      this.getUser();
    },
    //当前页发生变化触发的事件
    handleCurrentChange(page) {
      this.page=page;
      this.getUser();
    },
    //多选表格的选中状态发生变化触发的事件
    handleSelectionChange(value) {
      console.log(value, "表格选中的数据");
      this.selectId = value.map((item) => {
        item.id;
      });
    },
    //自定义的密码校验
    validatePassword(rule, value, callback) {
      if (!value) {
        callback("密码必须输入");
      } else if (!value || value.length < 6) {
        callback("密码不能小于6位");
      } else {
        callback();
      }
    },
    //点击添加对话框的确定按钮触发的事件
    addUser() {
      //点击确定按钮发起添加用户的请求前，进行表单的预验证
      this.$refs.ruleForm.validate(async (valid) => {
        console.log(valid, "valid");
        if (!valid) return;
        //正式发起添加用户的请求
        const result = await this.$API.user.addUser(this.Userform);
        console.log(result, "添加用户");
        if (result.code == 200) {
          this.$message({
            type: "success",
            message: "添加用户成功",
          });
        }
        this.adddialogFormVisible = false;
        this.getUser();
      });
    },
    //点击批量删除触发的事件
    async deletion() {
      const result = await this.$confirm(
        "此操作将永久删除选中项, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((error) => {
        return error;
      });
      console.log(result, "result");
      if (result !== "confirm") {
        this.$message.info("用户取消了删除操作");
      }
      //发起删除的请求
      const res = await this.$API.user.deleteUser(this.selectId);
      console.log(res, "删除的操作");
      if (res.code == 200) {
        this.$message.success("删除成功!");
      }
      this.getUser();
    },
    //点击分配角色按钮触发的事件
    showAssignRole(row) {
      console.log(row, "row");
      this.AssignRoledialogFormVisible = true;
      this.Roleform = row;

      //调用获取角色的请求
      this.getRoles(row.id);
    },
    //全选的状态发生改变触发的事件
    handleCheckAllChange(val) {
      console.log(val, "val"); //val当前勾选状态true/false
      this.userRoleIds = val ? this.allRoles.map((item) => item.id) : [];
    },
    //选中项发生变化触发的事件
    handleCheckedChange(value) {
      let checkedCount = value.length;
      console.log(checkedCount, "1111111");
      this.checkAll = checkedCount === this.allRoles.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.allRoles.length;
    },
    //获取某个用户所有的角色
    async getRoles(userId) {
      const result = await this.$API.user.reqgetRoles(userId);
      console.log(result, "获取所有的角色");
      if (result.code == 20000) {
        this.allRoles = result.data.allRolesList;
        this.userRoleIds = result.data.assignRoles.map((item) => item.id);
        console.log(this.userRoleIds, "用户的角色ID的列表");
      }
    },
    //点击分配角色对话框的确定按钮触发的事件
    async saveassignRole() {
      //拿到当前用户的id
      const userId = this.Roleform.id;
      //拿到当前用户下的角色id
      const roleId = this.userRoleIds.join(",");
      //发起分配角色的请求
      const result = await this.$API.user.assignRoles(userId, roleId);
      console.log(result, "分配角色");
      if (result.code == 20000) {
        this.$message.success("分配角色成功");
      }
      //关闭分配角色对话框
      this.AssignRoledialogFormVisible = false;
      this.getUser();
    },
    //点击修改用户的按钮触发的事件
    UpdateUser(row) {
      console.log(row, "row");
      this.Updateform = row;
      this.UpdatedialogFormVisible = true;
    },
    //点击修改用户对话框的确定按钮触发的事假
    ReviseUser(){
      //发起请求钱对表单进行预验证
      this.$refs.UpdateRef.validate(async (valid)=>{
        if(!valid) return;
        //正式发起修改用户提交的请求
        //拿到修改后的用户的信息
        const user=this.Updateform;
        const result=await this.$API.user.Update(user);
        console.log(result,"修改用户");
        if(result.code==200){
          this.$message.success('修改用户成功')
        }
        this.UpdatedialogFormVisible=false;
        this.getUser();
      })
    },
    //点击删除用户的按钮触发的事件
    async removeUser(id){
      const result=await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(error=>{
          return error;
        })
        if(result!=='confirm'){
          this.$message.info('用户取消了删除')
        }
        //发起删除的请求
        const res=await this.$API.user.removeById(id);
        console.log(res,"刪除用戶");
        if(res.code=200){
          this.$message.success('刪除成功');
        }
        this.getUser();
    }
  },
};
</script>
<style  scoped>
.tab {
  margin: 20px 0;
}
</style>